import { AIMessage, BaseMessage, HumanMessage, SystemMessage } from "@langchain/core/messages";
import { BaseListChatMessageHistory } from "@langchain/core/chat_history";
import { GenID } from "./utils";
import { Message } from "./services/domain/models/messages";

export class SqliteChatMessageHistory extends BaseListChatMessageHistory {
    lc_namespace: string[];
    private sessionId;
    private userID: string;
    contentType: "text" | "image";
    constructor(userID: string, sessionId: string) {
        super();
        this.userID = userID;
        this.sessionId = sessionId;
    }

    async addMessage(message: BaseMessage): Promise<void> {
        let msg = new Message();
        msg._id = GenID(10);
        msg.content = message.content as string;
        msg.type = message.getType() as any;
        msg.userID = this.userID;
        msg.convID = this.sessionId;
        msg.contentType = this.contentType;
        await msg.save();
    }

    async getMessages(): Promise<BaseMessage[]> {
        const list = await Message.findAll({
            where: {
                convID: this.sessionId
            },
            raw: true
        })
        return list.map((msg) => {
            // const baseMsg = msg as any;
            switch (msg.type) {
                case "user":
                    return new HumanMessage(msg.content);
                case "ai":
                    return new AIMessage(msg.content);
                // case "system":
                //     return new SystemMessage(baseMsg.content);
                default:
                    throw new Error(`Unsupported message type: ${msg.type}`);
            }
        });
    }
}